package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

/*
全局过滤器，校验token是否有效
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    /**
     * 执行过滤的方法
     * @param exchange 交换机，可以获取请求和响应对象
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       //TODO
        //1.判断是否为登录请求
        ServerHttpRequest request = exchange.getRequest();//获取请求对象
        ServerHttpResponse response = exchange.getResponse();//获取响应对象
        URI uri = request.getURI();
        String path = uri.getPath();//获取请求路径
        //1.1是登录请求，放行
        if (path.equals("/user/api/v1/login/login_auth/")){
            return chain.filter(exchange);    // /user/api/v1/login/login_auth/
        }
        //2.不是登录请求，判断是否含有token
        List<String> token = request.getHeaders().get("token");//获取请求头中的token
        //2.1不含token返回401
        if (token.isEmpty()){
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        }
        //2.2包含token，校验token是否有效，无效返回401，有效的话路由到微服务，结束
        Claims claimsBody = AppJwtUtil.getClaimsBody(token.get(0));
        int i = AppJwtUtil.verifyToken(claimsBody);
        if (i!=-1){
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 过滤的执行的优先级，返回值越小优先级越高
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
